const jwtUtils = require('../utils/jwtUtil')
// const redisUtil = require('../utils/redisUtil')
const tools = require('../utils/tools')
const mysqlUtil = require('../utils/mysqlUtil')

/**
 * 登录
 * @param req
 * @param resp
 */
let login = async (req,resp)=>{
    let query = req.query;
    let name = query.name;
    let pwd = query.pwd;



    // console.log(`会话ID:${req.sessionID}`)
    // console.log(`当前的会话用户名：${req.session.currentName},密码：${req.session.currentPwd}`)
    //
    // if(name === 'li' && pwd === '123'){
    //     let user = {id:'1',name:'li',school:'FZU',age:20,weight:60,height:160}
    //     await redisUtil.set(user.id,user,3600)
    //     resp.send(jwtUtils.sign({id:user.id},global.globalKey,3600))
    // } else {
    //     throw new Error('用户名或密码失败')
    // }
}

/**
 * 注册
 * @param req
 * @param resp
 */
let regist = async (req,resp)=>{
    let body = req.body;
    let name = body.name;
    let account = body.account;
    let pwd = body.pwd;
    if(!name || !account || !pwd){
        tools.error(resp,'关键参数丢失')
        return;
    }
    let tmp = await mysqlUtil.exec('select id from user where account=?',
        mysqlUtil.formatParams(account)
        )
    if(tmp.length != 0){
        tools.error(resp,'用户名已存在')
        return;
    }

    await mysqlUtil.exec('insert into user(id,name,account,pwd) values(?,?,?,?)',
        mysqlUtil.formatParams(tools.newId(),name,account,pwd))

    // global.currentname = name;
    // global.currentpwd = pwd;
    // req.session.currentName = name
    // req.session.currentPwd = pwd
    // console.log(`会话ID:${req.sessionID}`)
    resp.send('注册成功')
}

/**
 * 获取用户信息
 * @param req
 * @param resp
 */
let getUserInfo = (req,resp)=>{
    let header = req.headers;
    let token = header.token;
    let cookies = req.cookies;
    let li = cookies.li;
    resp.cookie('zhi',new Date().getTime())
    resp.send({
        name: req.query.name,
        class: 'xunke',
        token: token,
        li
    })
}

module.exports = {login,regist,getUserInfo}